/**********************************************
*  Classes:   ScriptManager
*  Desc:      Singleton class. Holds scripts and
*		      proxy functions to interface with 
*			  LUA.
*  Author:    Vaios Kalpias-Ilias (C) 2008-2009
***********************************************/

#ifndef SCRIPTMANAGER_H
#define SCRIPTMANAGER_H

extern "C" 
{
#include <lua.h>
}

#include <string>
#include <map>

class ScriptManager
{
public:
	// returns single instance
	static ScriptManager* GetInstance();
	// deletes instance and shuts down manager
	static  void Destroy();
	// initializes manager
	 bool Init();
	// resets manager
	 bool Reset();
	// loads script
	 bool Load(const std::string& name,
		      const std::string& filename);
	// unloads script
	 bool Unload(const std::string& name);
	// makes a script active to perform operations
	// on it
	 bool ActivateScript(const std::string& name);
	// executes the active script
	 bool ExecuteActiveScript()
	{
		if(lua_pcall(m_pActiveScript, 0, 
			LUA_MULTRET, 0))
		{
			return false;
		}

		return true;
	}
	// registers c++ function with a script
	 void ExportFunction(const char* funcName, lua_CFunction func);

	// returns the size of a table
	const  int GetTableSize(const char* table);

	// returns an int from the lua stack of the active
	// script
	const  int PopLuaInt(const char* var);
	
	// returns a float from the lua stack of the active
	// script
	const  float PopLuaFloat(const char* var);
	

	// returns a string from the lua stack of the active
	// script
	const  std::string PopLuaString(const char* var);

	// returns an int from a lua table from the active
	// script
	const  int PopLuaIntFromTable(const char* var, const char* table);

	// returns a float from a lua table from the active
	// script
	const  float PopLuaFloatFromTable(const char* var, const char* table);


	// returns a string from a lua table from the active
	// script
	const  std::string PopLuaStringFromTable(const char* var, const char* table);
	
	// returns index of top of lua stack
	const  int GetLuaTop() 
	{
		if (m_pActiveScript)
			return lua_gettop(m_pActiveScript);
		
		return -1;
	}

private:
	
	// single instance
	static  ScriptManager* m_spInstance;
	// map with Lua states. Each state holds a 
	// Lua script
	std::map<const std::string, lua_State*> m_Scripts;
	// active script
	lua_State* m_pActiveScript;
	
	// private ctor - dtor
	ScriptManager();
	~ScriptManager();

	// shuts down manager
	void  Shutdown();
};

#endif